package com.L.yygh.sms.Controller;

import com.L.yygh.common.result.Result;
import com.L.yygh.sms.Config.RandomUtil;
import com.L.yygh.sms.Service.SmsService;
import com.alibaba.excel.util.StringUtils;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
public class SmsController {
    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{phone}")
    public Result SendCode(@PathVariable String phone) throws TencentCloudSDKException {
        //从redis中获取验证码，如果获取到验证码，则返回OK
        //Key手机号，value验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }else{
            //如果redis中获取不到，则生成一个六位的随机数验证码
            code = RandomUtil.getSixBitRandom();
            //调用service方法，通过腾讯云短信服务进行发送
            boolean isSend = smsService.send(phone,code);
            //生成验证码放到redis里面，设置有效时间
            if(isSend) {
                redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
                return Result.ok();
            } else {
                return Result.fail().message("发送短信失败");
            }
        }
    }
}
